跳到主要内容

Python 基础语法

前言

本来是不想追赶潮流去学习什么 Python ,但是据说这个写爬虫效率比较高一些,加上一些识别库支持比较好,所以只能先放下 NodeJS 来学习下 Python 用来备用

写个 Hello World

在 Python 中,没有像其他编程语言(如 C++ 或 Java)中的 main 函数那样的特殊入口点。在 Python 中,脚本会从文件的第一行开始逐行执行。

然而,为了组织代码和定义可执行的入口点,通常会在 Python 脚本中使用一个条件判断来判断是否执行特定的代码块。这通常使用一个名为 if __name__ == "__main__" 的条件语句。

def main():
# 在这里编写你的主要逻辑
print("Hello, World!")

if __name__ == "__main__":
main()

在这个示例中,我们定义了一个名为 main 的函数,其中包含我们的主要逻辑,即打印 "Hello, World!"。然后,我们使用 if __name__ == "__main__" 条件语句来检查当前模块是否作为主程序执行。

如果当前模块是作为主程序执行,那么 __name__ 的值将是 "__main__",我们就调用 main 函数来执行我们的主要逻辑。如果当前模块被导入到其他模块中,__name__ 的值将是模块的名称,那么 main 函数就不会被执行。

这种方式使得我们可以将一些测试代码放在 main 函数中,并且只有当脚本作为主程序执行时才会运行这些代码。这样可以使代码更加模块化和可重用。

语法部分

头部信息

写 Linux 脚本已经学习过了,Linux 是根据文件开头的头部信息来执行的(在 Windows 下没有用)

#!/usr/bin/env python
# -*- coding:utf-8 -*-

或者

#!/usr/bin/python
# -*- coding:utf-8 -*-

注意:如果开头是

#%%

表示这个是 jupyte notebook

书写格式

Python 是使用缩进表示子级关系的(就像 yml)

# 但是在同一代码块中要使用相同数量的空格
if 5 > 2:
print("Five is greater than two!")

# 不能下面这样
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")

创建变量

甚至无需声明变量,首次为其赋值时,才会创建变量。

x = 5
# 字符串变量可以使用单引号或双引号
y = "Hello, World!"

# 向多个变量赋值
x, y, z = "Orange", "Banana", "Cherry"

# 在一行中为多个变量分配相同的值
x = y = z = "Orange"

# 支持字符拼接
x = "awesome"
print("Python is " + x)

全局变量

x = "awesome"

def myfunc():
print("Python is " + x)

myfunc()

global 关键字

# global 关键字可以在函数内部创建全局变量
def myfunc():
global x
x = "fantastic"

myfunc()

print("Python is " + x)

注释

使用 # 开头,Python 没有多行注释

虽然没有多行注释,但是可以用 """ 将字符串包住使之为一个字符串,勉强算是一个多行注释

"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")

逻辑语句

a = 66
b = 200
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")

# 缩写为一行
if a > b: print("a is greater than b")

# and or 语句表示与非

# 简写 If ... Else
print("A") if a > b else print("B")

# if 语句不能为空,如果要写无内容的 if 语句,使用 pass 语句来避免错误
if b > a:
pass

循环语句

# while 语句
# break 语句
i = 1
while i < 7:
print(i)
if i == 3:
break
i += 1

# continue 语句
i = 0
while i < 7:
i += 1
if i == 3:
continue
print(i)

# else 语句(通过使用 else 语句,当条件不再成立时,可以运行一次代码块)
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")



# for 循环
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
# 循环遍历单词 "banana" 中的字母:
for x in "banana":
print(x)

# 循环一组代码指定的次数(0-9)
for x in range(10):
print(x)

# 从 3 开始循环
for x in range(3, 10):
print(x)

# 使用 3 递增序列(默认值为 1)
for x in range(3, 50, 6):
print(x)
# 这个 for 也可以使用 else
for x in range(10):
print(x)
else:
print("Finally finished!")
# pass 语句(同 if,如果为空要写这个 pass)
for x in [0, 1, 2]:
pass

命令行读写

print("Enter your name:")
# 使用 input() 可以接收命令行的输入
x = input()
print("Hello ", x)

函数

普通函数

使用 def 关键字定义一个函数

def my_function(name):
print(name + " Gates")

# 调用
my_function("Rory John")


# 默认参数值
def my_function(country = "China"):
print("I am from " + country)

# 返回值
def my_function(x):
return 5 * x

print(my_function(3))


# 关键字参数(就是可以不按顺序传参,但是没啥卵用)
def my_function(child3, child2, child1):
print("The youngest child is " + child3)

my_function(child1 = "Phoebe", child2 = "Jennifer", child3 = "Rory")

# 任意参数(如果不知道要传多少参数可以使用 * 来声明,函数将接收一个参数元组)
def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Phoebe", "Jennifer", "Rory")

# 函数也不能为空,如果为空要使用 pass
def my_function:
pass

数据类型

类型名称关键字
文本类型:str
数值类型:int, float, complex
序列类型:list, tuple, range
映射类型:dict
集合类型:set, frozenset
布尔类型:bool
二进制类型:bytes, bytearray, memoryview

可以使用 type() 方法获取数据类型

x = 10
print(type(x))

声明不同类型的变量

示例数据类型
x = "Hello World"str
x = 29int
x = 29.5float
x = 1jcomplex
x = ["apple", "banana", "cherry"]list
x = ("apple", "banana", "cherry")tuple
x = range(6)range
x = {"name" : "Bill", "age" : 63}dict
x = {"apple", "banana", "cherry"}set
x = frozenset({"apple", "banana", "cherry"})frozenset
x = Truebool
x = b"Hello"bytes
x = bytearray(5)bytearray
x = memoryview(bytes(5))memoryview

设定特定的数据类型

示例数据类型
x = str("Hello World")str
x = int(29)int
x = float(29.5)float
x = complex(1j)complex
x = list(("apple", "banana", "cherry"))list
x = tuple(("apple", "banana", "cherry"))tuple
x = range(6)range
x = dict(name="Bill", age=36)dict
x = set(("apple", "banana", "cherry"))set
x = frozenset(("apple", "banana", "cherry"))frozenset
x = bool(5)bool
x = bytes(5)bytes
x = bytearray(5)bytearray
x = memoryview(bytes(5))memoryview